/**
 * 字典基础逻辑
 * */
import http from './request.js'
const DICTKEY = 'dict'
export default {
	name: 'dictMixins',
	methods: {
		/**
		 * 获取全部字典并保存
		 * */
		async fetchAllDict() {
			let resp = await http.post({
				url: '/enrollment/sysDict/getDictListByPage',
				data: {pageNum: 1, pageSize: 1000}
			})
			let dictCodes = resp.result.rows.map(item => {
			  return item.dictCode;
			});
			let dictResp = await http.post({
				url: '/enrollment/sysDict/getDictLists',
				data: JSON.stringify(dictCodes),
				header: {
					'content-type': 'application/json;charset=UTF-8'
				}
			})
			let allDicts = dictResp.result;
			let cashDicts = dictCodes.map((dictCode, index) => {
				let list = allDicts[index].map(item => {
					let obj = {
						name: item.dictName,
						value: item.dictValue,
						id: item.dictValue
					}
					return obj;
				})
				let dictInfo = {
					dictCode,
					list
				};
				return dictInfo;
			});
			uni.setStorageSync(DICTKEY, JSON.stringify(cashDicts));
			return cashDicts;
		},
		/**
		 * 根据字典dictCode和value获取名称
		 * */
		getDictNameWithCodeAndValue(dictCode, value) {
			let findDict = this.findOneDict(dictCode);
			if (!findDict)	return '';
			let findItem = findDict.list.filter(item => {
				return item.value == value;
			})[0]
			if (!findItem)	return '';
			let dictName = findItem.name;
			return dictName;
		},
		/**
		 * 获取字典
		 * @param {String} dictCode 字典code
		 * */
		findOneDict(dictCode) {
			let cashDicts;
			if (!uni.getStorageSync(DICTKEY)) {
				return;
			}
			cashDicts = JSON.parse(uni.getStorageSync(DICTKEY));
			let findDict = cashDicts.filter(item => {
				return item.dictCode == dictCode;
			})[0]
			// if (!findDict)	return `未找到${dictCode}字典`;
			if (!findDict)	return false;
			return findDict;
		},
		/**
		 * 获取字典的list数组
		 * @param {String} dictCode 字典code
		 * */
		findOneDictList(dictCode) {
			let findDict = this.findOneDict(dictCode);
			if (!findDict)	return `未找到${dictCode}字典`;
			return findDict.list;
		}
	}
}